package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size=10;
        }
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate()))
                        .limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                , ApCommentRepay.class);
        //   3. 检查是否登录
        //3.1 如果未登录直接 返回评论回复列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null || apCommentRepays==null || apCommentRepays.size()==0) {
            return ResponseResult.okResult(apCommentRepays);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        // 基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        List<String> repays = apCommentRepays.stream().map(ApCommentRepay::getCommentId).collect(Collectors.toList());
        List<ApCommentRepayLike> repayLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(repays)
                .and("authorId").is(user.getId())), ApCommentRepayLike.class);
        List<String> likeIds = repayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
        List<ApCommentRepayVO> repayVOS = new ArrayList<>();
        // 遍历 当前回复列表，将每一个回复信息 封装成 vo
        apCommentRepays.forEach(apCommentRepay -> {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
            // 判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            if (likeIds.contains(apCommentRepay.getId())) {
                apCommentRepayVO.setOperation((short) 0);
            }
            repayVOS.add(apCommentRepayVO);
        });
        return ResponseResult.okResult(apCommentRepays);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            //1. 参数校验:
            //是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
            //回复内容安全校验
            //简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String filteredContent = (String) map.get("filteredContent");
            if (filteredContent!=null) {
                dto.setContent(filteredContent);
            }
            //2. 根据评论id查询评论信息  检查是否存在
            ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
            if (!result.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
            }
            ApUser data = result.getData();
            if (data==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //3. 保存评论回复信息
            ApCommentRepay apCommentRepay = new ApCommentRepay();
            apCommentRepay.setCommentId(dto.getCommentId());
            apCommentRepay.setAuthorId(data.getId());
            apCommentRepay.setAuthorName(data.getName());
            apCommentRepay.setContent(dto.getContent());
            apCommentRepay.setLikes(0);
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
            //4. 修改评论信息中回复数量 + 1
            ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            comment.setReply(comment.getReply()+1);
            mongoTemplate.save(comment);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //回复id不能为空   operation 必须 0 或 1
        //校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验回复信息是否存在
        ApCommentRepay repay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (repay==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApCommentRepayLike repayLikes = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId())
                .and("commentRepayId").is(repay.getId())), ApCommentRepayLike.class);
        //2. 如果是点赞  判断是否点过赞
        if (dto.getOperation()==0) {
            if (repayLikes != null) {
                //点过赞提示请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已点赞");
            }
            //未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(dto.getOperation());
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
            //并将回复信息的点赞数量字段+1
            repay.setLikes(repay.getLikes()+1);
            mongoTemplate.save(repay);
        }else {
            //3. 如果是取消赞
            if (repayLikes == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"请先点赞");
            }
            repay.setLikes(repay.getLikes()<=0 ? 0 : repay.getLikes()-1);
            //删除点赞信息
            mongoTemplate.save(repay);
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(repay.getId())), ApCommentRepayLike.class);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("likes",repay.getLikes());
        return ResponseResult.okResult(map);
    }
}
